package swt.solutions;

import org.eclipse.jface.dialogs.InputDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeItem;

public class SWTTreeExercise{

	
	public static void main(String[] args) {
		
		Display display = Display.getDefault();
		final Shell shell = new Shell(display);
		shell.setLayout(new FillLayout());
		final Tree tree = new Tree(shell, SWT.V_SCROLL);
		
		for (int i=0; i<5;i++) {
			TreeItem item = new TreeItem(tree, SWT.NONE);
			item.setText("Item " + i );
			
			for (int j=0; j<3;j++) {
				TreeItem subItem = new TreeItem(item, SWT.NONE);
				subItem.setText("Subitem " + i + "." + j);
			}
			
		}
		tree.pack();
		
		Menu menu = new Menu(tree);
		MenuItem menuPrintItem = new MenuItem(menu, SWT.NONE);
		
		menuPrintItem.setText("Print Element");
		menuPrintItem.addSelectionListener(new SelectionAdapter() {
			
			public void widgetSelected(SelectionEvent event) {
				TreeItem selection = tree.getSelection()[0];
				MessageBox mb = new MessageBox(shell, SWT.ICON_WARNING);
				mb.setMessage(selection.getText());
				mb.open();
			}
		});
		MenuItem menuDeleteItem = new MenuItem(menu, SWT.NONE);
		
		menuDeleteItem.setText("Delete Element");
		menuDeleteItem.addSelectionListener(new SelectionAdapter() {
			
			public void widgetSelected(SelectionEvent event) {
				TreeItem selection = tree.getSelection()[0];
				
				selection.dispose();				
			}
		});
		MenuItem menuAddItem = new MenuItem(menu, SWT.NONE);
		
		menuAddItem.setText("Add Element");
		menuAddItem.addSelectionListener(new SelectionAdapter() {
			
			public void widgetSelected(SelectionEvent event) {
				TreeItem selection = tree.getSelection()[0];
				InputDialog inputDialog = new InputDialog(shell, "Add Item", "Enter name of new item", "", null);
				if(inputDialog.open() == InputDialog.OK){
					TreeItem subItem = new TreeItem(selection, SWT.NONE);
					subItem.setText(inputDialog.getValue());
				}
			}
		});
		tree.setMenu(menu);		
		
		shell.pack ();
		shell.open ();

		while (!shell.isDisposed()) {
			if (!display.readAndDispatch())
				display.sleep();
		}
		display.dispose();
	}

}



